<template>
  <div class="app-container">
    <div style="display: flex;margin-bottom: 20px">
      <el-button
        v-waves
        :loading="downloadLoading"
        style="background-color: #4ab7bd;border-color: #4ab7bd"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
      >
        <a
          href="http://81.70.41.226:8006/UploadFile/Files/用户信息上传模板.xlsx"
          target="_blank"
        >请先下载用户信息上传模板</a>
      </el-button>
      <span style="text-align: center;margin-top: 15px;margin-left: 20px;">导入用户默认密码：P@ssw0rd</span>
    </div>
    <div>
      <el-input
        style="width: 70%;float: left;"
        size="small"
        v-model="ResourceUrl"
        placeholder="文件名称"
        readonly
        disabled
      />
      <el-upload
        class="avatar-uploader"
        :action="actionUrl"
        :show-file-list="false"
        :on-success="handleMainSuccess"
        :before-upload="beforeMainUpload"
        :headers="headers"
        style="width: 10%;float: left;"
      >
        <el-button type="primary" :loading="loading" size="small">点击上传</el-button>
      </el-upload>
    </div>
    <div style="margin-top: 15px; display: flex;align-items: center;clear:both;">
      <span style="color: #FF0000;margin-left: 30px">失败总记录条数：{{ failItemCount }}</span>
    </div>
    <div v-if="failItemCount>0" style="margin-top: 15px; margin-left: 30px;">
      <el-button type="primary">
        <a :href="failUrl" target="_blank">导出失败用户列表</a>
      </el-button>
    </div>
    <div style="margin-top: 15px; margin-left: 30px;">
      <span style="color: #FF0000">上传失败数据列表(默认显示前100条)：</span>
    </div>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      fit
      border
      highlight-current-row
      style="width: 100%;margin-top:20px;"
      height="250"
    >
      <el-table-column label="登录名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.LoginName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.MobilePhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          <span>
            <span>{{ scope.row.UserName }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.Remark }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { insertAdminUsers } from "@/api/user";
// import UploadExcelComponent from "@/components/UploadExcel/index.vue";
import waves from "@/directive/waves"; // Waves directiv
import BackToTop from "@/components/BackToTop";
import { getToken, removeToken } from '@/utils/auth'

export default {
  name: "SGMWInfoUpload",
  components: { BackToTop },
  directives: { waves },
  watch: {
    dateText(val) {
      this.list = [];
      this.ResourceUrl = ''
      this.loading = false
      this.failItemCount = 0
      this.failUrl = '#'
    }
  },
  props: {
    dateText: String,
    ac: String
  },
  data() {
    return {
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: '',
      ResourceUrl: '',
      studentList: [],
      userType: "JXS",
      downloadLoading: false,
      loading: false,
      list: [],
      failUrl: '#',
      listLoading: false,
      tableKey: 0,
      headers: {},
      allItemCount: 0,
      successItemCount: 0,
      failItemCount: 0
    };
  },
  created() {
    this.actionUrl = this.apiPre + '/Student/InsertSGMWAdminUsers?userType=STUDENT'
    this.userType = this.ac
    this.setheaders()
  },
  methods: {
    setheaders() {
      this.headers = {
        Authorization: getToken()
      }
    },
    handleMainSuccess(res, file) {//资源上传完成响应方法   
      this.loading = false
      if (res && res.code != 200) {
        this.$notify({
          title: "失败",
          message: "上传失败!",
          type: "error",
          duration: 3000
        });
        return
      }
      this.list = res.data.list.failed;
      this.failUrl = res.data.url
      // alert(res.data.url)
      this.failItemCount = res.data.list.failedCount;
      this.$notify({
        title: "成功",
        message: "上传完成!",
        type: "success",
        duration: 3000
      });

    },
    beforeMainUpload(file) {
      this.loading = true
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]
      if (ext !== "xls" && ext !== "xlsx" && ext !== "csv") {
        this.$notify({
          title: "失败",
          message: "上传资源只能是 xls/xlsx/csv 格式!",
          type: "error",
          duration: 3000
        });
        this.loading = false
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$notify({
          title: "失败",
          message: "上传文件大小不能超过 5MB!",
          type: "error",
          duration: 3000
        });
        this.loading = false
        return false
      }
      this.ResourceUrl = fileName
    },
    beforeUpload(file) {
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]
      if (ext !== "xls" && ext !== "xlsx" && ext !== "csv") {
        this.$notify({
          title: "失败",
          message: "上传资源只能是 xls/xlsx/csv 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      const isLtnM = file.size / 1024 / 1024 < 100;
      if (!isLtnM) {
        this.$notify({
          title: "失败",
          message: "上传资源大小不能超过100MB!",
          type: "error",
          duration: 3000
        });
        return false
      }
      return true
    },
    handleSuccess({ results, header }) {
      // results.forEach((item, index) => {
      //   const student = {};
      //   Object.keys(item).forEach(key => {
      //     if (key === "sno") {
      //       student.sno = String(item[key]);
      //     }
      //     if (key === "stuName") {
      //       student.stuName = item[key];
      //     }
      //     if (key === "stuSex") {
      //       student.stuSex = item[key];
      //     }
      //   });
      //   this.studentList.push(student);
      // });
      //this.studentList = results;
      console.log(results)
      this.insertStudentInfoList(results);
    },
    //插入数据库学生信息表
    async insertStudentInfoList(data) {
      this.listLoading = true;
      const result = await insertAdminUsers(data, this.userType);
      if (result.code === 200) {
        this.list = result.data.list.failed;
        this.allItemCount = data.length;
        this.successItemCount = result.data.list.succeed.length;
        this.failItemCount = result.data.list.failed.length;

        this.$notify({
          title: "成功",
          message: result.data.msg,
          type: "success",
          duration: 3000
        });
        this.listLoading = false;
      } else {
        this.list = result.data.list.failed;
        this.allItemCount = data.length;
        this.successItemCount = result.data.list.succeed.length;
        this.failItemCount = result.data.list.failed.length;

        this.$notify({
          title: "失败",
          message: result.data.msg,
          type: "error",
          duration: 3000
        });
        this.listLoading = false;
      }
    }
  }
};
</script>


<style lang="stylus" type="text/stylus" rel="stylesheet/stylus" scoped></style>